package ernie.server.context;

import java.io.IOException;

import misc.JSONStringStream;
import misc.JsonEncodable;
import net.sourceforge.javajson.JsonArray;
import net.sourceforge.javajson.JsonObject;
import stock.nordnet.NordNetDirektDepo;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

/**
 * @author Filip
 */
public class MyNordnetDirektDepoContext implements HttpHandler {
    private final NordNetDirektDepo depo;

    public MyNordnetDirektDepoContext() {
        depo = new NordNetDirektDepo();
        //depo.startSchedule();
    }

    @Override
    public void handle(HttpExchange he) {
        JsonArray stocks = new JsonArray();
        JSONStringStream hss = new JSONStringStream(he);
        if (depo.getResultCache().isEmpty()) {
            stocks.add("No registered stocks!");
        } else {
            for (JsonEncodable jsonEncodable : depo.getResultCache()) {
                JsonObject jo = new JsonObject();
                jsonEncodable.putJSON(jo);
                stocks.add(jo);
            }
        }
        try {
            hss.write(stocks);
            hss.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
